﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using NursingFormSystem.Model;
using NursingFormSystem.Common;
using DLL;
using Common;
using SQLDLL;

namespace NursingFormSystem.KnowingAgreeBook
{
    public partial class AddAgreeBookNursing : DevExpress.XtraEditors.XtraForm
    {
        NursingFormRecord record = new NursingFormRecord();
        NurFormsService.NursingForm formService = new NurFormsService.NursingForm();
        PatientInfo PatientInfo;
        string Id;
        public Tb_User LoginUser;
        public AddAgreeBookNursing(Tb_User loginUser, PatientInfo patientInfo)
        {
            InitializeComponent();
            //成员变量赋值
            this.LoginUser = loginUser;
            this.PatientInfo = patientInfo;

            //电签
            ElectronicSignature();

            //绑定数据
            BindInfo(this.Id);
        }
        public AddAgreeBookNursing(string[] loginUser, string[] patientInfo)
        {
            InitializeComponent();
            //成员变量赋值
            this.LoginUser = ArrayToObject.ArrayToLoginUser(loginUser);
            this.PatientInfo = ArrayToObject.ArrayToPatientInfo(patientInfo);

            //电签
            ElectronicSignature();

            //绑定数据
            BindInfo(this.Id);
        }
        /// <summary>
        /// 初始化加载印章图片
        /// </summary>
        private void ElectronicSignature()
        {
            ElectronicSignature es = new ElectronicSignature(LoginUser);
            es.SearchElectronicSignatureImage(Base.ESSwitch, LoginUser, txtHuShiQianMing, picElectronicSignature, txtHuShiQianMing.Location);
        }

        #region 绑定数据
        /// <summary>
        /// 绑定数据 进入更新模式
        /// </summary>
        /// <param name="id"></param>
        private void BindInfo(string id)
        {
            //0升序 1降序
            var ret = formService.GetNursingFormRecordOrderByTime(PatientInfo.PATIENT_ID, PatientInfo.VISIT_ID, (int)FormType.Knowing, 1);
            if (ret.Code == 1)
            {
                List<NursingFormRecord> list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<NursingFormRecord>>(ret.D);
                if (string.IsNullOrEmpty(id))
                    record = list[0];
                else
                    record = list.Find(p => p.Id == Convert.ToInt32(id));
                this.Id = record.Id.ToString();
                var NursingFormData = record.NursingFormData;
                Knowing ps = new Knowing();
                ps = XmlUtil.XMLToObject<Knowing>(NursingFormData, Encoding.UTF8);
                //约束工具的应用
                txtYY_QiTa.Text = ps.YueShuGongJu.YY_QiTa;//原因-其他
                txtYF_QiTa.Text = ps.YueShuGongJu.YF_QiTa;//预防-其他
                txtBFZ_QiTa.Text = ps.YueShuGongJu.BFZ_QiTa;//并发症-其他
                var YuanYin = ps.YueShuGongJu.YuanYin.Split('#'); //原因
                if (YuanYin[0] == "1")
                    cheYuanYin1.Checked = true;
                else
                    cheYuanYin1.Checked = false;
                if (YuanYin[1] == "1")
                    cheYuanYin2.Checked = true;
                else
                    cheYuanYin2.Checked = false;
                if (YuanYin[2] == "1")
                    cheYuanYin3.Checked = true;
                else
                    cheYuanYin3.Checked = false;
                if (YuanYin[3] == "1")
                    cheYuanYin4.Checked = true;
                else
                    cheYuanYin4.Checked = false;
                var YuFang = ps.YueShuGongJu.YuFang.Split('#'); //预防
                if (YuFang[0] == "1")
                    cheYuFang1.Checked = true;
                else
                    cheYuFang1.Checked = false;
                if (YuFang[1] == "1")
                    cheYuFang2.Checked = true;
                else
                    cheYuFang2.Checked = false;
                if (YuFang[2] == "1")
                    cheYuFang3.Checked = true;
                else
                    cheYuFang3.Checked = false;
                if (YuFang[3] == "1")
                    cheYuFang4.Checked = true;
                else
                    cheYuFang4.Checked = false;
                if (YuFang[4] == "1")
                    cheYuFang5.Checked = true;
                else
                    cheYuFang5.Checked = false;
                var BingFaZheng = ps.YueShuGongJu.BingFaZheng.Split('#'); //并发症
                if (BingFaZheng[0] == "1")
                    cheBingFaZheng1.Checked = true;
                else
                    cheBingFaZheng1.Checked = false;
                if (BingFaZheng[1] == "1")
                    cheBingFaZheng2.Checked = true;
                else
                    cheBingFaZheng2.Checked = false;
                if (BingFaZheng[2] == "1")
                    cheBingFaZheng3.Checked = true;
                else
                    cheBingFaZheng3.Checked = false;
                if (BingFaZheng[3] == "1")
                    cheBingFaZheng4.Checked = true;
                else
                    cheBingFaZheng4.Checked = false;

                //24小时看护（患方）
                txtYSZA_QiTa.Text = ps.ErShiSiXiaoShiKanHu.YSZA_QiTa;//意识障碍-其他
                txtJSZA_QiTa.Text = ps.ErShiSiXiaoShiKanHu.JSZA_QiTa;//精神障碍-其他
                txtNL_QiTa.Text = ps.ErShiSiXiaoShiKanHu.NL_QiTa;//年龄-其他
                txtYF_QiTa1.Text = ps.ErShiSiXiaoShiKanHu.YF_QiTa;//预防-其他
                var YiShiZhangAi = ps.ErShiSiXiaoShiKanHu.YiShiZhangAi.Split('#'); //意识障碍
                if (YiShiZhangAi[0] == "1")
                    cheYiShiZhangAi1.Checked = true;
                else
                    cheYiShiZhangAi1.Checked = false;
                if (YiShiZhangAi[1] == "1")
                    cheYiShiZhangAi2.Checked = true;
                else
                    cheYiShiZhangAi2.Checked = false;
                if (YiShiZhangAi[2] == "1")
                    cheYiShiZhangAi3.Checked = true;
                else
                    cheYiShiZhangAi3.Checked = false;
                if (YiShiZhangAi[3] == "1")
                    cheYiShiZhangAi4.Checked = true;
                else
                    cheYiShiZhangAi4.Checked = false;
                var JingShenZhangAi = ps.ErShiSiXiaoShiKanHu.JingShenZhangAi.Split('#'); //精神障碍
                if (JingShenZhangAi[0] == "1")
                    cheJingShenZhangAi1.Checked = true;
                else
                    cheJingShenZhangAi1.Checked = false;
                if (JingShenZhangAi[1] == "1")
                    cheJingShenZhangAi2.Checked = true;
                else
                    cheJingShenZhangAi2.Checked = false;
                if (JingShenZhangAi[2] == "1")
                    cheJingShenZhangAi3.Checked = true;
                else
                    cheJingShenZhangAi3.Checked = false;
                var NianLin = ps.ErShiSiXiaoShiKanHu.NianLin.Split('#'); ////年龄
                if (NianLin[0] == "1")
                    cheNianLin1.Checked = true;
                else
                    cheNianLin1.Checked = false;
                if (NianLin[1] == "1")
                    cheNianLin2.Checked = true;
                else
                    cheNianLin2.Checked = false;
                var YuFang1 = ps.ErShiSiXiaoShiKanHu.YuFang.Split('#'); //预防
                if (YuFang1[0] == "1")
                    cheYuFang11.Checked = true;
                else
                    cheYuFang11.Checked = false;
                if (YuFang1[1] == "1")
                    cheYuFang22.Checked = true;
                else
                    cheYuFang22.Checked = false;
                if (YuFang1[2] == "1")
                    cheYuFang33.Checked = true;
                else
                    cheYuFang33.Checked = false;
                if (YuFang1[3] == "1")
                    cheYuFang44.Checked = true;
                else
                    cheYuFang44.Checked = false;
                if (YuFang1[4] == "1")
                    cheYuFang55.Checked = true;
                else
                    cheYuFang55.Checked = false;
                if (YuFang1[5] == "1")
                    cheYuFang66.Checked = true;
                else
                    cheYuFang66.Checked = false;

                //尾部
                txtJiaShuYiJian.Text = ps.JiaShuYiJian;//家属意见
                txtQianMing.Text = ps.QianMing;//签名
                txtYuHuanZheGuanXi.Text = ps.YuHuanZheGuanXi;//与患者关系
                txtHuShiQianMing.Text = ps.HuShiQianMing;//护士签名
                if (!string.IsNullOrEmpty(ps.RiQi))
                    DateE_RiQi.DateTime = Convert.ToDateTime(ps.RiQi);//日期
                else
                    DateE_RiQi.DateTime = DateTime.Now;
            }
            else if (ret.Code == 2)
            {
                InsertMode(false);
                return;
            }
            else
            {
                MessageBox.Show(ret.M);
            }
        }
        #endregion

        #region 保存事件
        /// <summary>
        /// 保存事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(DateE_RiQi.Text))
                DateE_RiQi.DateTime = DateTime.Now;

            Knowing bc = new Knowing();
            bc.FormId = (int)FormType.Knowing;
            bc.FormName = EnumHelper.GetDescription(FormType.Knowing);
            //约束工具的应用
            bc.YueShuGongJu.YY_QiTa = txtYY_QiTa.Text;//原因-其他
            bc.YueShuGongJu.YF_QiTa = txtYF_QiTa.Text;//预防-其他
            bc.YueShuGongJu.BFZ_QiTa = txtBFZ_QiTa.Text;//并发症-其他
            bc.YueShuGongJu.YuanYin = (cheYuanYin1.Checked ? "1" : "0") + "#" + (cheYuanYin2.Checked ? "1" : "0") + "#" + (cheYuanYin3.Checked ? "1" : "0") + "#" + (cheYuanYin4.Checked ? "1" : "0");//原因
            bc.YueShuGongJu.YuFang = (cheYuFang1.Checked ? "1" : "0") + "#" + (cheYuFang2.Checked ? "1" : "0") + "#" + (cheYuFang3.Checked ? "1" : "0") + "#" + (cheYuFang4.Checked ? "1" : "0") + "#" + (cheYuFang5.Checked ? "1" : "0");//预防
            bc.YueShuGongJu.BingFaZheng = (cheBingFaZheng1.Checked ? "1" : "0") + "#" + (cheBingFaZheng2.Checked ? "1" : "0") + "#" + (cheBingFaZheng3.Checked ? "1" : "0") + "#" + (cheBingFaZheng4.Checked ? "1" : "0");//并发症

            //24小时看护（患方）
            bc.ErShiSiXiaoShiKanHu.YSZA_QiTa = txtYSZA_QiTa.Text;//意识障碍-其他
            bc.ErShiSiXiaoShiKanHu.JSZA_QiTa = txtJSZA_QiTa.Text;//精神障碍-其他
            bc.ErShiSiXiaoShiKanHu.NL_QiTa = txtNL_QiTa.Text;//年龄-其他
            bc.ErShiSiXiaoShiKanHu.YF_QiTa = txtYF_QiTa1.Text;//预防-其他
            bc.ErShiSiXiaoShiKanHu.YiShiZhangAi = (cheYiShiZhangAi1.Checked ? "1" : "0") + "#" + (cheYiShiZhangAi2.Checked ? "1" : "0") + "#" + (cheYiShiZhangAi3.Checked ? "1" : "0") + "#" + (cheYiShiZhangAi4.Checked ? "1" : "0");//意识障碍
            bc.ErShiSiXiaoShiKanHu.JingShenZhangAi = (cheJingShenZhangAi1.Checked ? "1" : "0") + "#" + (cheJingShenZhangAi2.Checked ? "1" : "0") + "#" + (cheJingShenZhangAi3.Checked ? "1" : "0");//精神障碍
            bc.ErShiSiXiaoShiKanHu.NianLin = (cheNianLin1.Checked ? "1" : "0") + "#" + (cheNianLin2.Checked ? "1" : "0");//年龄
            bc.ErShiSiXiaoShiKanHu.YuFang = (cheYuFang11.Checked ? "1" : "0") + "#" + (cheYuFang22.Checked ? "1" : "0") + "#" + (cheYuFang33.Checked ? "1" : "0") + "#" + (cheYuFang44.Checked ? "1" : "0") + "#" + (cheYuFang55.Checked ? "1" : "0") + "#" + (cheYuFang66.Checked ? "1" : "0");//预防

            //尾部
            bc.JiaShuYiJian = txtJiaShuYiJian.Text;//家属意见
            bc.QianMing = txtQianMing.Text;//家属签名
            bc.YuHuanZheGuanXi = txtYuHuanZheGuanXi.Text;//与患者关系
            if (string.IsNullOrEmpty(this.Id))
                bc.HuShiQianMing = LoginUser.UserName;//护士签名
            else
                bc.HuShiQianMing = txtHuShiQianMing.Text;
            bc.RiQi = DateE_RiQi.DateTime.ToString("yyyy-MM-dd HH:mm:ss");//日期
            record.NursingFormData = XmlUtil.ObjectToXML(bc, Encoding.UTF8);
            record.FormId = bc.FormId;//表单ID
            record.FormName = bc.FormName;//表单NAME
            record.PatientId = PatientInfo.PATIENT_ID;//住院号
            record.VisitId = PatientInfo.VISIT_ID;//住院次数
            record.PatientName = PatientInfo.PATIENT_NAME;//患者名称
            record.BedNo = PatientInfo.BED_NO;//床号
            record.DepartmentId = PatientInfo.DEPARTMENT_ID;//科室号
            record.DepartmentName = PatientInfo.DEPARTMENT_NAME;//科室名称
            record.AreaId = PatientInfo.NURSE_CELL_CODE;//病区编号
            record.AreaName = PatientInfo.NURSE_CELL_NAME;//病区名称
            record.AssessmentDate = DateE_RiQi.DateTime;//日期       

            record.Id = string.IsNullOrEmpty(Id) ? 0 : Convert.ToInt32(Id);
            var ret = formService.SetNursingFormRecord(Newtonsoft.Json.JsonConvert.SerializeObject(record));

            if (ret.Code == 1)
            {
                //电签开始
                if (Base.ESSwitch.Equals("on"))
                {
                    string extraInfo = "<?xml version=\"1.0\" encoding=\"UTF-16\"?><root><sign_sys>{0}</sign_sys><title>{1}</title><patient_id>{2}</patient_id><patient_name>{3}</patient_name><emr_id>{4}</emr_id><emr_catalog>{5}</emr_catalog><his_id>{6}</his_id><event_no>{7}</event_no><visit_number>{8}</visit_number><dept_name>{9}</dept_name><prescribe_number>{10}</prescribe_number><prescribe_sub_number>{11}</prescribe_sub_number><prescribe_operation>医嘱操作（发送、校对、停止、作废）或门诊处方操作（发送）</prescribe_operation><radiotherapy_id>放疗号</radiotherapy_id><process_name>CT定位申请单审核</process_name><process_time>CT定位申请单审核时间</process_time><extend_value_1>备用扩展1</extend_value_1><extend_value_2>备用扩展2</extend_value_2><extend_value_3>备用扩展3</extend_value_3><extend_value_4>备用扩展4</extend_value_4><extend_value_5>备用扩展5</extend_value_5><extend_value_6>备用扩展6</extend_value_6><extend_value_7>备用扩展7</extend_value_7><extend_value_8>备用扩展8</extend_value_8><extend_value_9>备用扩展9</extend_value_9></root>";
                    extraInfo = string.Format(extraInfo, EnumHelper.GetDescription(FormType.Knowing) + (record.Id > 0 ? "-更新" : "-新增"), EnumHelper.GetDescription(FormType.Knowing), record.PatientId, record.PatientName, record.Id, record.FormId, "", record.PatientId, record.VisitId, LoginUser.DepartmentName, record.PatientId, record.PatientId);
                    ElectronicSignature es = new ElectronicSignature(LoginUser);
                    bool res = es.GetElectronicSignatureImage(es, record.NursingFormData, extraInfo, ((int)FormType.Knowing).ToString(), EnumHelper.GetDescription(FormType.Knowing), PatientInfo.PATIENT_ID, PatientInfo.VISIT_ID);
                    if (!res) { MessageBox.Show("电子签名失败"); return; }
                }
                MessageBox.Show(record.Id == 0 ? "新增成功" : "更新成功");
                if (record.Id > 0) return;
                //新增成功后绑定数据
                this.Id = string.Empty;
                BindInfo(this.Id);
            }
            else
            {
                MessageBox.Show(ret.M);
            }
            this.DialogResult = DialogResult.OK;
        }
        #endregion

        #region 刷新事件
        /// <summary>
        /// 刷新事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.Id)) { MessageBox.Show("当前为新增模式，无法操作"); return; }
            BindInfo(this.Id);
        }
        #endregion

        #region enter键当做Tab
        /// <summary>
        /// 设置 enter键当做Tab切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void TemperatureEdit1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                SendKeys.SendWait("{Tab}");
            }
        }
        #endregion

        #region 打印事件
        /// <summary>
        /// 打印事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.Id)) { MessageBox.Show("当前为新增模式，无法操作"); return; }
            AgreeBookPrints f = new AgreeBookPrints(LoginUser, PatientInfo, this.Id);
            f.ShowDialog();
        }
        #endregion

        #region 删除事件
        /// <summary>
        /// 删除事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDel_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.Id)) { MessageBox.Show("当前为新增模式，无法操作"); return; }
            if (MessageBox.Show("确定要删除数据吗？", "删除前确认", MessageBoxButtons.OKCancel) != DialogResult.OK) return;

            var ret = formService.DeleteNursingFormRecord(this.Id);
            MessageBox.Show(ret.M);
            if (ret.Code != 1) return;

            this.Id = string.Empty;
            BindInfo(this.Id);
        }
        /// <summary>
        /// 没有记录单的时候
        /// </summary>
        private void ShowClose()
        {
            MessageBox.Show(string.Format("该患者没有《{0}》 \r\n 自动转入新增界面", EnumHelper.GetDescription(FormType.Knowing)),
                            "关闭提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            InsertMode(false);
        }
        #endregion

        #region 历史按钮 新增按钮事件
        /// <summary>
        /// 历史记录按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnHis_Click(object sender, EventArgs e)
        {
            HistoryKAB f = new HistoryKAB(this.PatientInfo);
            f.ShowDialog();
            if (f.DialogResult != DialogResult.OK) return;
            if (string.IsNullOrEmpty(f.Id)) return;
            this.Id = f.Id;
            BindInfo(this.Id);
        }
        /// <summary>
        /// 新增按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNew_Click(object sender, EventArgs e)
        {
            InsertMode(true);
        }
        #endregion

        #region 进入新增模式和清除控件值
        /// <summary>
        /// 进入新增模式
        /// </summary>
        /// <param name="openTips">是否需要先来个提示</param>
        private void InsertMode(bool openTips)
        {
            if (openTips && MessageBox.Show("是否新增该表单", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
                return;
            foreach (Control c in groupControl5.Controls)
                ControlValueClear(c);
            foreach (Control c in groupControl1.Controls)
                ControlValueClear(c);
            foreach (Control c in pnlHisPatiens.Controls)
                ControlValueClear(c);

            DateE_RiQi.DateTime = DateTime.Now;
            txtHuShiQianMing.Text = this.LoginUser.UserName;
            record = new NursingFormRecord();
            this.Id = string.Empty;
        }
        /// <summary>
        /// 清除控件值
        /// </summary>
        /// <param name="c"></param>
        private static void ControlValueClear(Control c)
        {
            if (c is TextEdit)
                ((TextEdit)c).Text = string.Empty;
            if (c is CheckEdit)
                ((CheckEdit)c).Checked = false;
        }
        #endregion

    }
}